package com.mspbots.sync.wise.client;

import com.mspbots.sync.model.TenantConfiguration;
import lombok.Data;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * com.mspbots.sync.scheduled.connectwise.aaa
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/6/28
 * <p>
 * your ConnectWise application configuration
 */
@Data
public class ClientProperties {

    /**
     * The integrator’s ConnectWise Application Id.
     */
    @NotEmpty
    private String appId;

    /**
     * The ConnectWise Application URL.
     */
    @NotEmpty
    private String site;

    /**
     * Found on the API Key tab on a member record or under My Account.
     */
    @NotEmpty
    private String publicKey;

    /**
     * Found on the API Key tab on a member record or under My Account.
     */
    @NotEmpty
    private String privateKey;

    /**
     * Found on the tenant id.
     */
    @NotEmpty
    private Integer tenantId;

    @NotEmpty
    private String clientId = "b9feb0a1-787c-46b9-9d85-b6f60e2b927a";


    public static Mono<ClientProperties> build(List<TenantConfiguration> configurations) {
        if (configurations != null && configurations.size() > 0) {
            Map<String, String> map = configurations.parallelStream()
                    .filter(config -> config.getKeyword().startsWith("mspbots.sync.wise"))
                    .filter(c -> !StringUtils.isEmpty(c.getKeywordValue()))
                    .collect(Collectors.toMap(TenantConfiguration::getKeyword, TenantConfiguration::getKeywordValue));

            if (map.size() == 0) {
                return Mono.empty();
            }

            ClientProperties connectWiseConfiguration = new ClientProperties();
            connectWiseConfiguration.setTenantId(configurations.get(0).getTenantId());
            connectWiseConfiguration.setAppId(map.get("mspbots.sync.wise.appId"));
            connectWiseConfiguration.setSite(map.get("mspbots.sync.wise.site"));
            connectWiseConfiguration.setPublicKey(map.get("mspbots.sync.wise.publicKey"));
            connectWiseConfiguration.setPrivateKey(map.get("mspbots.sync.wise.privateKey"));
            return Mono.just(connectWiseConfiguration);
        }
        return Mono.empty();
    }


}
